package common

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"math/rand"
	"net/http"
	"strings"
)

func RandomInRange(min, max int) int {
	return min + rand.Intn(max-min)
}

func HttpRequest(url string, method string, header map[string]string, body io.Reader) ([]byte, *http.Header, error) {
	client := http.Client{}
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, nil, err
	}
	if header != nil {
		for k, v := range header {
			req.Header.Set(k, v)
		}
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, nil, err
	}
	defer func(readCloser io.ReadCloser) {
		_ = readCloser.Close()
	}(resp.Body)

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, nil, err
	}
	return respBody, &resp.Header, nil
}

func PostRequest(url string, jsonReq []byte) ([]byte, error) {
	// 构建HTTP请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonReq))
	if err != nil {
		return nil, fmt.Errorf("error creating request: %w", err)
	}
	// 设置请求头
	req.Header.Set("Content-Type", "application/json")

	// 执行请求
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("error making request: %w", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	return io.ReadAll(resp.Body)
}

func GetMainUrl(ctx *gin.Context) (string, bool) {
	mainUrl, ok := getMainUrl(ctx.Request.Referer())
	if !ok {
		mainUrl, ok = getMainUrl(ctx.GetHeader("origin"))
	}
	return mainUrl, ok
}

func getMainUrl(url string) (string, bool) {
	if strings.EqualFold(url, "") {
		return "", false
	}
	url = strings.TrimSpace(url)
	urlArr := strings.Split(url, "//")
	if len(urlArr) < 2 || strings.EqualFold(urlArr[1], "") {
		return "", false
	}
	return strings.TrimRight(urlArr[1], "/"), true
}
func GetAirWallexRedisAccessToken(xClientId string) string {
	return fmt.Sprintf("simplifly:airwallex-cache:%s", xClientId)
}
